package org.mdrtwell.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectTester {
	public Object copyObject(Object obj) throws Exception {
		Class<?> clazz = obj.getClass();
		Object objCopy = clazz.getConstructor(new Class[] {}).newInstance(new Object[] {});
		for (Field field : clazz.getDeclaredFields()) {
			String fieldName = field.getName();
			String firstCha = fieldName.substring(0, 1).toUpperCase();
			String getMethodName = "get" + firstCha + fieldName.substring(1);
			String setMethodName = "set" + firstCha + fieldName.substring(1);
			Method getMethod = clazz.getMethod(getMethodName, new Class[] {});
			Method setMethod = clazz.getMethod(setMethodName, new Class[] { field.getType() });
			Object value = getMethod.invoke(obj, new Object[] {});
			setMethod.invoke(objCopy, new Object[] { value });
		}
		return objCopy;
	}

	public static void main(String[] args) throws Exception {
		Customer customer = new Customer("Tom", 21);
		customer.setId(new Long(1));
		Customer customerCopy = (Customer) new ReflectTester().copyObject(customer);
		System.out.println("Copy information:" + customerCopy.getId() + " "
				+ customerCopy.getName() + " " + customerCopy.getAge());
	}
}

class Customer {
	private Long	id;
	private String	name;
	private int		age;

	public Customer() {
	}

	public Customer(String name,
			int age) {
		this.name = name;
		this.age = age;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}
